//
// membercache.cs: A container for all member lookups
//
// Author: Miguel de Icaza (miguel@gnu.org)
//         Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2010 Novell, Inc
// Copyright 2011 Xamarin Inc
//
//

using System;
using System.Collections.Generic;

namespace Teal.Compiler {

	[Flags]
	public enum MemberKind
	{
		Constructor = 1,
		Event = 1 << 1,
		Field = 1 << 2,
		Method = 1 << 3,
		Property = 1 << 4,
		Indexer = 1 << 5,
		Operator = 1 << 6,
		Destructor	= 1 << 7,

		Class		= 1 << 11,
		Struct		= 1 << 12,
		Delegate	= 1 << 13,
		Enum		= 1 << 14,
		Interface	= 1 << 15,
		TypeParameter = 1 << 16,

		ArrayType = 1 << 19,
		PointerType = 1 << 20,
		InternalCompilerType = 1 << 21,
		MissingType = 1 << 22,
		Void = 1 << 23,
		Namespace = 1 << 24,

		NestedMask = Class | Struct | Delegate | Enum | Interface,
		GenericMask = Method | Class | Struct | Delegate | Interface,
		MaskType = Constructor | Event | Field | Method | Property | Indexer | Operator | Destructor | NestedMask
	}

	[Flags]
	public enum BindingRestriction
	{
		None = 0,

		// Inspect only queried type members
		DeclaredOnly = 1 << 1,

		// Exclude static
		InstanceOnly = 1 << 2,

		NoAccessors = 1 << 3,

		// Member has to be override
		OverrideOnly = 1 << 4
	}

	public struct MemberFilter : IEquatable<MemberReference>
	{
		public readonly string Name;
		public readonly MemberKind Kind;
		public readonly AParametersCollection Parameters;
		public readonly TypeReference MemberType;
		public readonly int Arity; // -1 to ignore the check

		public MemberFilter (MethodReference m)
		{
			Name = m.name;
			Kind = MemberKind.Method;
			Parameters = m.Parameters;
			MemberType = m.ReturnType;
			Arity = m.genericParameterCount;
		}

		public MemberFilter (string name, int arity, MemberKind kind, AParametersCollection param, TypeReference type)
		{
			Name = name;
			Kind = kind;
			Parameters = param;
			MemberType = type;
			this.Arity = arity;
		}

		public static MemberFilter Constructor (AParametersCollection param)
		{
			return new MemberFilter (Teal.Compiler.ConstructorDefinition.ConstructorName, 0, MemberKind.Constructor, param, null);
		}

		public static MemberFilter Property (string name, TypeReference type)
		{
			return new MemberFilter (name, 0, MemberKind.Property, null, type);
		}

		public static MemberFilter Field (string name, TypeReference type)
		{
			return new MemberFilter (name, 0, MemberKind.Field, null, type);
		}

		public static MemberFilter Method (string name, int arity, AParametersCollection param, TypeReference type)
		{
			return new MemberFilter (name, arity, MemberKind.Method, param, type);
		}

		#region IEquatable<MemberSpec> Members

		public bool Equals (MemberReference other)
		{
			// Is the member of the correct type ?
			// TODO: Isn't this redundant ?
			if ((other.Kind & Kind & MemberKind.MaskType) == 0)
				return false;

			// Check arity when not disabled
			if (Arity >= 0 && Arity != other.genericParameterCount)
				return false;

			if (Parameters != null) {
				if (other is IParametersMember) {
					var other_param = ((IParametersMember) other).Parameters;
					if (!TypeSpecComparer.Override.IsEqual (Parameters, other_param))
						return false;
				} else {
					return false;
				}
			}

			if (MemberType != null) {
				if (other is IInterfaceMemberSpec) {
                    var other_type = ((IInterfaceMemberSpec)other).MemberType2;
					if (!TypeSpecComparer.Override.IsEqual (other_type, MemberType))
						return false;
				} else {
					return false;
				}
			}

			return true;
		}

		#endregion
	}

	//
	// The MemberCache is the main members container used by compiler. It contains
	// all members imported or defined during compilation using on demand filling
	// process. Inflated containers are also using MemberCache to make inflated
	// members look like normal definition.
	//
	// All of the methods are performance and memory sensitive as the MemberCache
	// is the underlying engine of all member based operations.
	//
	public class MemberCache
	{
		[Flags]
		enum StateFlags
		{
			HasConversionOperator = 1 << 1,
			HasUserOperator = 1 << 2
		}

		readonly Dictionary<string, IList<MemberReference>> member_hash;
	    IList<MethodReference> missing_abstract;
		StateFlags state;	// TODO: Move to TypeSpec or ITypeDefinition

		public static readonly string IndexerNameAlias = "<this>";

		public static readonly MemberCache Empty = new MemberCache (0);

	    public MemberCache (int capacity)
		{
			member_hash = new Dictionary<string, IList<MemberReference>> (capacity);
		}

	    //
		// Creates a new MemberCache for the given `container'.
		//

	    //
		// Member-cache does not contain base members but it does
		// contain all base interface members, so the Lookup code
		// can use simple inheritance rules.
		//
		// Does not work recursively because of generic interfaces
		//

	    public void AddMember (MethodOrPropertyDefinition imb, string exlicitName, MemberReference ms)
		{
			// Explicit names cannot be looked-up but can be used for
			// collision checking (no name mangling needed)
			if (imb.explicitType != null)
				AddMember (exlicitName, ms, false);
			else
				AddMember (ms);
		}

		//
		// Add non-explicit member to member cache
		//
		public void AddMember (MemberReference ms)
		{
			AddMember (GetLookupName (ms), ms, false);
		}

		void AddMember (string name, MemberReference member, bool removeHiddenMembers)
		{
			if (member.Kind == MemberKind.Operator) {
				var dt = member.containerType;


				//
				// Some core types have user operators but they cannot be used like normal
				// user operators as they are predefined and therefore having different
				// rules (e.g. binary operators) by not setting the flag we hide them for
				// user conversions
				//
				if (!BuiltinTypeSpec.IsPrimitiveType (dt) || dt.BuiltinType == BuiltinTypeSpec.Type.Char) {
					switch (dt.BuiltinType) {
					case BuiltinTypeSpec.Type.String:
					case BuiltinTypeSpec.Type.Delegate:
					case BuiltinTypeSpec.Type.MulticastDelegate:
						break;
					default:
						if (name == OperatorDefinition.GetMetadataName (OperatorDefinition.OpType.Implicit) || name == OperatorDefinition.GetMetadataName (OperatorDefinition.OpType.Explicit)) {
							state |= StateFlags.HasConversionOperator;
						} else {
							state |= StateFlags.HasUserOperator;
						}

						break;
					}
				}
			}

			IList<MemberReference> list;
			if (!member_hash.TryGetValue (name, out list)) {
				member_hash.Add (name, new MemberReference[] { member });
				return;
			}

			if (removeHiddenMembers && member.containerType.IsInterface) {
				if (AddInterfaceMember (member, ref list))
					member_hash[name] = list;
			} else {
				if (list.Count == 1) {
					list = new List<MemberReference> { list[0] };
					member_hash[name] = list;
				}

				list.Add (member);
			}
		}

	    //
		// Ignores any base interface member which can be hidden
		// by this interface
		//
		static bool AddInterfaceMember (MemberReference member, ref IList<MemberReference> existing)
		{
			var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : ParametersCompiled.EmptyReadOnlyParameters;

			//
			// interface IA : IB { int Prop { set; } }
			// interface IB { bool Prop { get; } }
			//
			// IB.Prop is never accessible from IA interface
			//
			for (int i = 0; i < existing.Count; ++i) {
				var entry = existing[i];

                if (entry.genericParameterCount != member.genericParameterCount)
					continue;

				if (entry is IParametersMember) {
					var entry_param = ((IParametersMember) entry).Parameters;
					if (!TypeSpecComparer.Override.IsEqual (entry_param, member_param))
						continue;
				}

				if (member.containerType.ImplementsInterface (entry.containerType, false)) {
					if (existing.Count == 1) {
						existing = new MemberReference[] { member };
						return true;
					}

					existing.RemoveAt (i--);
					continue;
				}

				if ((entry.containerType == member.containerType && entry.IsAccessor == member.IsAccessor) ||
					entry.containerType.ImplementsInterface (member.containerType, false))
					return false;
			}

			if (existing.Count == 1) {
				existing = new List<MemberReference> { existing[0], member };
				return true;
			}

			existing.Add (member);
			return false;
		}

		public static MemberReference FindMember (TypeReference container, MemberFilter filter, BindingRestriction restrictions)
		{
			do {
				IList<MemberReference> applicable;
				if (container.MemberCache.member_hash.TryGetValue (filter.Name, out applicable)) {
					// Start from the end because interface members are in reverse order
					for (int i = applicable.Count - 1; i >= 0; i--) {
						var entry = applicable [i];

						if ((restrictions & BindingRestriction.InstanceOnly) != 0 && entry.isStatic)
							continue;

						if ((restrictions & BindingRestriction.NoAccessors) != 0 && entry.IsAccessor)
							continue;

						if ((restrictions & BindingRestriction.OverrideOnly) != 0 && (entry.modifiers & Modifiers.@override) == 0)
							continue;

						if (!filter.Equals (entry))
							continue;

						if ((restrictions & BindingRestriction.DeclaredOnly) != 0 && container.IsInterface && entry.containerType != container)
							continue;

						return entry;
					}
				}

				if ((restrictions & BindingRestriction.DeclaredOnly) != 0)
					break;

				container = container.baseClass;
			} while (container != null);

			return null;
		}

		//
		// A special method to work with member lookup only. It returns a list of all members named @name
		// starting from @container. It's very performance sensitive
		//
		// declaredOnlyClass cannot be used interfaces. Manual filtering is required because names are
		// compacted
		//
		public static IList<MemberReference> FindMembers (TypeReference container, string name, bool declaredOnlyClass)
		{
			IList<MemberReference> applicable;

			do {
				if (container.MemberCache.member_hash.TryGetValue (name, out applicable) || declaredOnlyClass)
					return applicable;

				container = container.baseClass;
			} while (container != null);

			return null;
		}

		//
		// Finds the nested type in container
		//
		public static TypeReference FindNestedType (TypeReference container, string name, int arity)
		{
			IList<MemberReference> applicable;
			TypeReference best_match = null;
			do {
#if !FULL_AOT_RUNTIME
				// TODO: Don't know how to handle this yet
				// When resolving base type of nested type, parent type must have
				// base type resolved to scan full hierarchy correctly
				// Similarly MemberCacheTypes will inflate BaseType and Interfaces
				// based on type definition
				var tc = container.MemberDefinition2 as MemberContainerDefinition;
				if (tc != null)
					tc.resolveBaseTypes ();
#endif

				if (container.MemberCacheTypes.member_hash.TryGetValue (name, out applicable)) {
					for (int i = applicable.Count - 1; i >= 0; i--) {
						var entry = applicable[i];
						if ((entry.Kind & MemberKind.NestedMask) == 0)
							continue;

						var ts = (TypeReference) entry;
						if (arity == ts.genericParameterCount)
							return ts;

						if (arity < 0) {
							if (best_match == null) {
								best_match = ts;
							} else if (System.Math.Abs (ts.genericParameterCount + arity) < System.Math.Abs (ts.genericParameterCount + arity)) {
								best_match = ts;
							}
						}
					}
				}

				container = container.baseClass;
			} while (container != null);

			return best_match;
		}

		//
		// Looks for extension methods with defined name and extension type
		//

	    //
		// Returns base members of @member member if no exact match is found @bestCandidate returns
		// the best match
		//
		public static MemberReference FindBaseMember (MemberDefinition member, out MemberReference bestCandidate, ref bool overrides)
		{
			bestCandidate = null;
			var container = member.container.PartialContainer.reference;
			if (!container.IsInterface) {
				container = container.baseClass;

				// It can happen for a user definition of System.Object
				if (container == null)
					return null;
			}

			string name = GetLookupName (member);
			var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : null;

			var mkind = GetMemberCoreKind (member);
			bool member_with_accessors = mkind == MemberKind.Indexer || mkind == MemberKind.Property;

			IList<MemberReference> applicable;
			MemberReference ambig_candidate = null;

			do {
				if (container.MemberCache.member_hash.TryGetValue (name, out applicable)) {
					for (int i = 0; i < applicable.Count; ++i) {
						var entry = applicable [i];

						if ((entry.modifiers & Modifiers.@public) == 0 && !entry.IsAccessible (member))
							continue;

						//
						// Isn't the member of same kind ?
						//
						if ((entry.Kind & ~MemberKind.Destructor & mkind & MemberKind.MaskType) == 0) {
							// Destructors are ignored as they cannot be overridden by user
							if ((entry.Kind & MemberKind.Destructor) != 0)
								continue;

							// A method with different arity does not hide base member
                            if (mkind != MemberKind.Method && member.MemberName.Arity != entry.genericParameterCount)
								continue;

							bestCandidate = entry;
							return null;
						}

						//
						// Same kind of different arity is valid
						//
                        if (member.MemberName.Arity != entry.genericParameterCount) {
							continue;
						}

						if ((entry.Kind & mkind & (MemberKind.Method | MemberKind.Indexer)) != 0) {
							if (entry.IsAccessor != member is AbstractPropertyEventMethod)
								continue;

							var pm = entry as IParametersMember;
							if (!TypeSpecComparer.Override.IsEqual (pm.Parameters, member_param))
								continue;
						}

						//
						// Skip override for member with accessors. It may not fully implement the base member
						// but keep flag we found an implementation in case the base member is abstract
						//
						if (member_with_accessors && ((entry.modifiers & (Modifiers.@override | Modifiers.final)) == Modifiers.@override)) {
							//
							// Set candidate to override implementation to flag we found an implementation
							//
							overrides = true;
							continue;
						}

						//
						// For members with parameters we can encounter an ambiguous candidates (they match exactly)
						// because generic type parameters could be inflated into same types
						//
						if (ambig_candidate == null && (entry.Kind & mkind & (MemberKind.Method | MemberKind.Indexer)) != 0) {
							bestCandidate = null;
							ambig_candidate = entry;
							continue;
						}

						bestCandidate = ambig_candidate;
						return entry;
					}
				}

				if (container.IsInterface || ambig_candidate != null)
					break;

				container = container.baseClass;
			} while (container != null);

			return ambig_candidate;
		}

		//
		// Returns inflated version of MemberSpec, it works similarly to
		// SRE TypeBuilder.GetMethod
		//
		public static T GetMember<T> (TypeReference container, T spec) where T : MemberReference
		{
			IList<MemberReference> applicable;
			if (container.MemberCache.member_hash.TryGetValue (GetLookupName (spec), out applicable)) {
				for (int i = applicable.Count - 1; i >= 0; i--) {
					var entry = applicable[i];
					if (entry.MemberDefinition2 == spec.MemberDefinition2)
						return (T) entry;
				}
			}

			throw new InternalErrorException ("Missing member `{0}' on inflated type `{1}'",
				spec.GetSignatureForError (), container.GetSignatureForError ());
		}

		static MemberKind GetMemberCoreKind (MemberDefinition member)
		{
			if (member is FieldDefinition)
				return MemberKind.Field;
			if (member is IndexerDefinition)
				return MemberKind.Indexer;
			if (member is ClassDefinition)
				return MemberKind.Class;
			if (member is StructDefinition)
				return MemberKind.Struct;
			if (member is DestructorDefinition)
				return MemberKind.Destructor;
			if (member is MethodDefinition)
				return MemberKind.Method;
			if (member is PropertyDefinition)
				return MemberKind.Property;
			if (member is EventFieldDefinition)
				return MemberKind.Event;
			if (member is InterfaceDefinition)
				return MemberKind.Interface;
			if (member is EventProperty)
				return MemberKind.Event;
			if (member is Delegate)
				return MemberKind.Delegate;
			if (member is EnumDefinition)
				return MemberKind.Enum;

			throw new NotImplementedException (member.GetType ().ToString ());
		}

		public static List<FieldReference> GetAllFieldsForDefiniteAssignment (TypeReference container)
		{
			List<FieldReference> fields = null;
			foreach (var entry in container.MemberCache.member_hash) {
				foreach (var name_entry in entry.Value) {
					if (name_entry.Kind != MemberKind.Field)
						continue;

					if ((name_entry.modifiers & Modifiers.@static) != 0)
						continue;

					//
					// Ignore user private fields for definite assignment. This is sort of unexpected but
					// rationale is to have consistent results when using reference assemblies which don't
					// include any private fields and full assemblies
					//
					if ((name_entry.modifiers & (Modifiers.@private | Modifiers.BACKING_FIELD)) == Modifiers.@private)
						continue;

					//
					// Fixed size buffers are not subject to definite assignment checking
					//
					if (name_entry.getAnnotation(PredefinedTypes.System_RunTime_FixedBufferAnnotation) != null || name_entry is ConstSpec)
						continue;

					var fs = (FieldReference) name_entry;

					//
					// LAMESPEC: Very bizzare hack, definitive assignment is not done
					// for imported non-public reference fields except array. No idea what the
					// actual csc rule is
					//
					if (!fs.isPublic && container.MemberDefinition2.IsImported && (!fs.MemberType2.IsArray && TypeReference.IsReferenceType (fs.MemberType2)))
						continue;

					//if ((fs.Modifiers & (Modifiers.BACKING_FIELD) != 0)
					//	continue;

					if (fields == null)
						fields = new List<FieldReference> ();

					fields.Add (fs);
					break;
				}
			}

			return fields ?? new List<FieldReference> (0);
		}

		public static IList<MemberReference> GetCompletitionMembers (IMemberContext ctx, TypeReference container, string name)
		{
			var matches = new List<MemberReference> ();
			foreach (var entry in container.MemberCache.member_hash) {
				foreach (var name_entry in entry.Value) {
					if (name_entry.IsAccessor)
						continue;

					if ((name_entry.Kind & (MemberKind.Constructor | MemberKind.Destructor | MemberKind.Operator)) != 0)
						continue;

					if (!name_entry.IsAccessible (ctx))
						continue;

					if (name == null || name_entry.name.StartsWith (name)) {
						matches.Add (name_entry);
					}
				}
			}

			return matches;
		}

		//
		// Returns members of @iface only, base members are ignored
		//
		public static List<MethodReference> GetInterfaceMethods (TypeReference iface)
		{
			//
			// MemberCache flatten interfaces, therefore in cases like this one
			// 
			// interface IA : IB {}
			// interface IB { void Foo () }
			//
			// we would return Foo inside IA which is not expected in this case
			//
			var methods = new List<MethodReference> ();
			foreach (var entry in iface.MemberCache.member_hash.Values) {
				foreach (var name_entry in entry) {
					if (iface == name_entry.containerType) {
						if (name_entry.Kind == MemberKind.Method) {
							methods.Add ((MethodReference) name_entry);
						}
					}
				}
			}

			return methods;
		}

		//
		// Returns all not implememted abstract members inside abstract type
		// NOTE: Returned list is shared and must not be modified
		//
		public static IList<MethodReference> GetNotImplementedAbstractMethods (TypeReference type)
		{
            return null;
            //if (type.MemberCache.missing_abstract != null)
            //    return type.MemberCache.missing_abstract;
				
            //var abstract_methods = new List<MethodReference> ();
            //List<TypeReference> hierarchy = null;

            ////
            //// Stage 1: top-to-bottom scan for abstract members
            ////
            //var abstract_type = type;
            //while (true) {
            //    foreach (var entry in abstract_type.MemberCache.member_hash) {
            //        foreach (var name_entry in entry.Value) {
            //            if ((name_entry.modifiers & Modifiers.@abstract) == 0)
            //                continue;

            //            var ms = name_entry as MethodReference;
            //            if (ms == null)
            //                continue;

            //            abstract_methods.Add (ms);
            //        }
            //    }

            //    var base_type = abstract_type.baseClass;
            //    if (!base_type.IsAbstract)
            //        break;

            //    if (hierarchy == null)
            //        hierarchy = new List<TypeReference> ();

            //    hierarchy.Add (abstract_type);
            //    abstract_type = base_type;
            //}

            //int not_implemented_count = abstract_methods.Count;
            //if (not_implemented_count == 0 || hierarchy == null) {
            //    type.MemberCache.missing_abstract = abstract_methods;
            //    return type.MemberCache.missing_abstract;
            //}

            ////
            //// Stage 2: Remove already implemented methods
            ////
            //foreach (var type_up in hierarchy) {
            //    var members = type_up.MemberCache.member_hash;
            //    if (members.Count == 0)
            //        continue;

            //    for (int i = 0; i < abstract_methods.Count; ++i) {
            //        var candidate = abstract_methods [i];
            //        if (candidate == null)
            //            continue;

            //        IList<MemberReference> applicable;
            //        if (!members.TryGetValue (candidate.name, out applicable))
            //            continue;

            //        var filter = new MemberFilter (candidate);
            //        foreach (var item in applicable) {
            //            if ((item.modifiers & (Modifiers.@override | Modifiers.@virtual)) == 0)
            //                continue;

            //            //
            //            // Abstract override does not override anything
            //            //
            //            if ((item.modifiers & Modifiers.@abstract) != 0)
            //                continue;

            //            if (filter.Equals (item)) {
            //                --not_implemented_count;
            //                abstract_methods [i] = null;
            //                break;
            //            }
            //        }
            //    }
            //}

            //if (not_implemented_count == abstract_methods.Count) {
            //    type.MemberCache.missing_abstract = abstract_methods;
            //    return type.MemberCache.missing_abstract;
            //}

            //var not_implemented = new MethodReference[not_implemented_count];
            //int counter = 0;
            //foreach (var m in abstract_methods) {
            //    if (m == null)
            //        continue;

            //    not_implemented[counter++] = m;
            //}

            //type.MemberCache.missing_abstract = not_implemented;
            //return type.MemberCache.missing_abstract;
		}

		static string GetLookupName (MemberReference ms)
		{
			if (ms.Kind == MemberKind.Indexer)
				return IndexerNameAlias;

			if (ms.Kind == MemberKind.Constructor) {
				if (ms.isStatic)
					return ConstructorDefinition.TypeConstructorName;

				return ConstructorDefinition.ConstructorName;
			}

			return ms.name;
		}

		static string GetLookupName (MemberDefinition mc)
		{
			if (mc is IndexerDefinition)
				return IndexerNameAlias;

			if (mc is ConstructorDefinition)
				return mc.IsStatic ? ConstructorDefinition.TypeConstructorName : ConstructorDefinition.ConstructorName;

			return mc.MemberName.Name;
		}

		//
		// Returns all operators declared on container and its base types (until declaredOnly is used)
		//
		public static IList<MemberReference> GetUserOperator (TypeReference container, OperatorDefinition.OpType op, bool declaredOnly)
		{
			IList<MemberReference> found = null;
			bool shared_list = true;
			IList<MemberReference> applicable;
			do {
				var mc = container.MemberCache;

				if (((op == OperatorDefinition.OpType.Implicit || op == OperatorDefinition.OpType.Explicit) && (mc.state & StateFlags.HasConversionOperator) != 0) ||
					 (mc.state & StateFlags.HasUserOperator) != 0) {

					if (mc.member_hash.TryGetValue (OperatorDefinition.GetMetadataName (op), out applicable)) {
						int i;
						for (i = 0; i < applicable.Count; ++i) {
							if (applicable[i].Kind != MemberKind.Operator) {
								break;
							}
						}

						//
						// Handles very rare case where a method with same name as operator (op_xxxx) exists
						// and we have to resize the applicable list
						//
						if (i != applicable.Count) {
							for (i = 0; i < applicable.Count; ++i) {
								if (applicable[i].Kind != MemberKind.Operator) {
									continue;
								}

								if (found == null) {
									found = new List<MemberReference> ();
									found.Add (applicable[i]);
								} else {
									List<MemberReference> prev;
									if (shared_list) {
										shared_list = false;
										prev = new List<MemberReference> (found.Count + 1);
										prev.AddRange (found);
									} else {
										prev = (List<MemberReference>) found;
									}

									prev.Add (applicable[i]);
								}
							}
						} else {
							if (found == null) {
								found = applicable;
								shared_list = true;
							} else {
								List<MemberReference> merged;
								if (shared_list) {
									shared_list = false;
									merged = new List<MemberReference> (found.Count + applicable.Count);
									merged.AddRange (found);
									found = merged;
								} else {
									merged = (List<MemberReference>) found;
								}

								merged.AddRange (applicable);
							}
						}
					}
				}

				// BaseType call can be expensive
				if (declaredOnly)
					break;

				container = container.baseClass;
			} while (container != null);

			return found;
		}

		//
		// Removes hidden base members of an interface. For compiled interfaces we cannot
		// do name filtering during Add (as we do for import) because we need all base
		// names to be valid during type definition.
		// Add replaces hidden base member with current one which means any name collision
		// (CS0108) of non-first name would be unnoticed because the name was replaced
		// with the one from compiled type
		//
		public void RemoveHiddenMembers (TypeReference container)
		{
			foreach (var entry in member_hash) {
				var values = entry.Value;

				int container_members_start_at = 0;
				while (values[container_members_start_at].containerType != container && ++container_members_start_at < entry.Value.Count);

				if (container_members_start_at == 0 || container_members_start_at == values.Count)
					continue;

				for (int i = 0; i < container_members_start_at; ++i) {
					var member = values[i];

					if (!container.ImplementsInterface (member.containerType, false))
						continue;

					var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : ParametersCompiled.EmptyReadOnlyParameters;

					for (int ii = container_members_start_at; ii < values.Count; ++ii) {
						var container_entry = values[ii];

                        if (container_entry.genericParameterCount != member.genericParameterCount)
							continue;

						if (container_entry is IParametersMember) {
							if (!TypeSpecComparer.Override.IsEqual (((IParametersMember) container_entry).Parameters, member_param))
								continue;
						}

						values.RemoveAt (i);
						--container_members_start_at;
						--ii;
						--i;
					}
				}
			}
		}

		//
		// Checks all appropriate container members for CLS compliance
		//

	    //
		// Local report helper to issue correctly ordered members stored in hashtable
		//

	    public bool CheckExistingMembersOverloads (MemberDefinition member, AParametersCollection parameters)
		{
			var name = GetLookupName (member);
			var imb = member as MethodOrPropertyDefinition;
			if (imb != null && imb.explicitType != null) {
				name = imb.GetFullName (name);
			}

			return true;
		}
	}
}
